const {
  openLoading,
  closeLoading,
  to,
  showToast,
  backParentLoad
} = getApp()
const {
  addFeedback
} = require('../../../api/feedback')
const {
  queryWorkOrderById
} = require('../../../api/workOrder')
Page({
  data: {
    judgeDescripe: '',
    formData: {
      starClass: '',
      feedbackContent: ''
    },
    orderData: {}
  },

  onLoad() {
    this.getUserDataById()
  },

  onChange(event) {
    const rateLabel = ['非常差', '差', '一般', '好', '非常好']
    this.setData({
      ['formData.starClass']: event.detail,
      judgeDescripe: rateLabel[event.detail - 1]
    })
  },

  async getUserDataById() {
    const params = {
      workOrderId: this.options.workOrderId
    };
    openLoading()
    const [err, data] = await to(queryWorkOrderById(params));
    closeLoading()
    if (!err) {
      this.setData({
        orderData: data
      })
    }
  },

  handleFieldChange(event) {
    this.setData({
      ['formData.feedbackContent']: event.detail
    })
  },

  checkValidate() {
    const {
      starClass,
      feedbackContent
    } = this.data.formData;

    if (!starClass) {
      showToast('请选择服务星级')
      return false
    }

    if (!feedbackContent) {
      showToast('请填写评价内容')
      return false
    }

    return true
  },

  async handlePublish() {
    const isValidate = this.checkValidate()

    if (!isValidate) return
    const {
      orderData,
      formData
    } = this.data
    const params = {
      workOrderId: orderData.workOrderId,
      ...formData
    }
    openLoading()
    const [err] = await to(addFeedback(params))
    closeLoading()

    if (!err) {
      showToast({
        message: '发布成功',
        type: 'success',
        mask: true,
        onClose: () => {
          setTimeout(() => {
            backParentLoad(1)
          }, 1000)
        }
      })
    }
  }
})